﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using WebAPI.Dao;

namespace WebAPI.Filter;

public class UserAuthorizationFilter : ActionFilterAttribute
{
    // Action 方法前调用
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var descriptor = context.ActionDescriptor as ControllerActionDescriptor;

        if (!(descriptor.ActionName == "UserLogin") && !(descriptor.ActionName == "UserRegister"))
        {
            string headersAuthorization = context.HttpContext.Request.Headers.Authorization;
            if (headersAuthorization == "" || headersAuthorization == null || headersAuthorization == "undefined")
            {
                Dictionary<string, object> map = new Dictionary<string, object>();
                map.Add("data", "用户还未授权，请先登录");
                
                context.Result = new UnauthorizedObjectResult(JsonConvert.ToJsonString(map));

                return;
            }
            else
            {
                try
                {
                    IDictionary<string,object> jwtDecode = JwtHelper.GetJwtDecode(headersAuthorization);
                    
                    foreach (string key in jwtDecode.Keys)
                    {
                        Console.WriteLine(key + ":" + jwtDecode[key]);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Dictionary<string, object> map = new Dictionary<string, object>();
                    map.Add("data", "用户认证已过期，请重新登录");
                
                    context.Result = new UnauthorizedObjectResult(JsonConvert.ToJsonString(map));
                    // throw;
                }
            }
        }

        base.OnActionExecuting(context);
    }

    // Action 方法后调用
    public override void OnActionExecuted(ActionExecutedContext context)
    {
        base.OnActionExecuted(context);
    }

    // Result 方法前调用
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        base.OnResultExecuting(context);
    }

    // Result 方法后调用
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        // var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
        //    
        // string result = string.Empty;
        // if (context.Result is ObjectResult)
        // {
        //     result = Newtonsoft.Json.JsonConvert.SerializeObject(((ObjectResult)context.Result).Value);
        // }
        //
        // Console.WriteLine($"webapi方法名称【{descriptor.ActionName}】执行的返回值 :  {result}");
        base.OnResultExecuted(context);
    }
}